/* *************前端控制层************* */
let axios = require('axios')
// 淘宝查询IP接口
const url = 'http://ip.taobao.com/outGetIpInfo'
// IP地址
let ipAddress = ''
let Operator = ''

let Home = require('../api/Home/index')
let Public = require('../api/index')
let code = { code: 200, message: '成功', data: null }
let err_code = { code: 201, message: '失败' }

function IPSelect(ip){
    // 查询ip地址
    axios.get(url,{params:{ip,accessKey:'alibaba-inc'}})
        .then(async val =>{
            if(val.data.code == 0){
                ipAddress = `${val.data.data.country}-${val.data.data.region}省-${val.data.data.city}市` 
                Operator = val.data.data.isp
                try {
                    await Public.addIp(ip,Operator,ipAddress)
                    console.log('成功将访问者保存')
                } catch (error) {
                  console.log('已保存访问者过')
                }
            }else{
              console.log('没有获取到访问者信息')
            }
        }).catch(err =>{
          console.log('查询ip错误')
        })
}

// 获取用户信息
exports.userInfo = async (req, res) => {
  try {
    // 传入的格式是: ’::ffff:117.139.132.185‘ ，截取成: 117.139.132.185
    let ip = req.clientIp.substring(7)
    // 调用保存访问者信息的函数
    IPSelect(ip)
    const result = await Home.userInfo()
    code.data = result[0]
    code.message = '成功'
    res.send(code)
  } catch (error) {
    catchFn(error, res)
  }
}

//根据文章id查询对应文章的具体内容，
exports.getArticleById = async (req, res) => {
  try {
    let id = req.body.id
    const result = await Home.selectBlogById(id)
      code.data = result
      code.message = '成功'
      res.send(code)
  } catch (error) {
    catchFn(error, res)
  }
}


// 获取指定id博客的所有留言
exports.onlyRep = async  (req, res) => {
  try {
    let { id } = req.body
    const result = await Home.onlyRepByBlog(id)
      code.data = result
      code.message = '成功'
      res.send(code)
  } catch (error) {
    catchFn(error, res)
  }
}

// 新增指定博客内的留言
exports.addPostCommentsByBlog = async (req, res) =>{
  try {
    let {id, name, content, email } = req.body
    const result = await Home.addCommentByBlog(id, name, content, email)
      code.data = result.insertId
      code.message = '成功'
      res.send(code)
  } catch (error) {
    catchFn(error, res)
  }
}

// 保存博客内容留言的评论的回复
exports.addReplyComment = async (req, res) =>{
  try {
    let {id, name, content, email, replyId } = req.body
    const result = await Home.addReplyComment(id, name, content, email, replyId)
      code.data = result.insertId
      code.message = '成功'
      res.send(code)
  } catch (error) {
    catchFn(error, res)
  }
}


//新增留言
exports.addPostComments = async (req, res) => {
  try {
    let { name, content, email } = req.body
    const result = await Home.addComment(name, content, email)
    code.data = result.insertId
    code.message = '成功'
    res.send(code)
  } catch (error) {
    catchFn(error, res)
  }
}



// 分页获取博客列表
exports.pageBlog = async (req, res) => {
  let { page } = req.body
  try {
    // 博客列表
    const resultArr = await Home.pageBlog(page)
    // 总博客数
    const allBlogSize = await Home.getBlogNum()
    // 中留言表中获取所有属于博客详情内容的文章
    const blogCommentArr = await Home.getBlogComment()

    // 中留言表数组中根据当前博客id去找对应的留言数据的articleId,找到则当前博客留言加1
    resultArr.forEach(currentBlog =>{
      let commentNum = blogCommentArr.reduce((pre,val) =>{
        if(val.articleId == currentBlog.id){
          return pre+=1
        }
        return pre
      },0)
      currentBlog.commentNum = commentNum
    })
    code.data = {}
    code.data.result = resultArr
    code.data.pageSize = allBlogSize[0].length
    code.message = '成功'
    res.send(code)
  } catch (error) {
    catchFn(error, res)
  }
}

// 分页获取留言列表
exports.pageRep = async (req, res) => {
  try {
    let { page } = req.body
    const result = await Home.pageRep(page)
    const allRepSize = await Home.getRepNum()
    code.data = {}
    code.data.result = result
    code.data.pageSize = allRepSize[0].length
    code.message = '成功'
    res.send(code)
  } catch (error) {
    catchFn(error, res)
  }
}

// 获取博客详情页内留言
exports.getCommentByBlog = async (req, res) =>{
  let { id } = req.body
  try {
    let result = await Home.getCommentByBlog(id)
      code.data = result
      code.message = '成功'
      res.send(code)
  } catch (error) {
    catchFn(error, res)
  }
}

// 获取博客内容评论的回复信息
exports.getReplyComment = async (req, res) =>{
  let { id } = req.body
  try {
    let comment 
    let result = await Home.getReplyComment(id)
    // 查询博客详情页内被回复的评论用户名
    if(result.length > 0){
      for (let index = 0; index < result.length; index++) {
        const element = result[index];
        comment = await Home.getByReplyCommentName(element.replyId) 
        result[index].byReplyName = comment[0].name
      }
    }
      code.data = result
      code.message = '成功'
      res.send(code)
  } catch (error) {
    catchFn(error, res)
  }
}

// 获取当前浏览博客的后各一条博客内容
exports.getCurrentBlogNext = async (req, res) => {
  try {
    let { id } = req.body
    const result = await Home.getCurrentBlogNext(id)
    if ( result && result.length != 0){
      code.message = '成功'
      code.data = result[0].id
      res.send(code)
    }else if( result && result.length == 0){
      err_code.message = '无更多博客信息'
      res.send(err_code)
    }
    // else{
    //   res.send(result)
    // }
  } catch (error) {
    catchFn(error, res)
  }
}

// 点赞接口
exports.addAgree = async (req, res) => {
  handleOpposeOrAgree(req, res, '请勿重复点赞', 'add', 'reduce')
}

// 反对接口
exports.addOppose = async (req, res) => {
  handleOpposeOrAgree(req, res, '请勿重复反对', 'reduce', 'add')
}

// 反对/赞同操作封装的函数
async function handleOpposeOrAgree(req, res, message, HandleAgreeStr, HandleOpposeStr) {
  let { flag, id } = req.body
  let userIp = req.clientIp
  // 返回的是数组，如果长度不为0，则表示当前用户之前操作过当前点赞的这条评论（点赞/反对了）
  let isExist
  let result
  try {
    isExist = await Home.isExist(userIp, id)
    if (isExist.length === 0) {
      // 没有操作过当前的评论,直接添加到ip表中,flag为0,并且反对数数+1
      result = await Home.addIpInIpTable(userIp, flag, id)
      // 是点赞操作
      if (message === '请勿重复点赞') {
        result && await Home.HandleAgree(id, 'add')
        code.message = '点赞成功'
      } else {
        code.message = '反对成功'
        result && await Home.HandleOppose(id, 'add')
      }
      code.data = 1
      res.send(code)
    } else if (isExist.length !== 0 && isExist[0].flag == flag) {
      // 操作过，提示勿重复操作
      err_code.message = message
      res.send(err_code)
    } else {
      // 以反对接口为例: 原本该评论当前用户是赞同 isExist[0].flag为1，现在是反对 
      /**
       * 1、先修改flag，改为 0
       * 2、将反对数+1 ，点赞数 -1
       */
      await Home.UpdateIPTableFlag(flag, id)
      await Home.HandleAgree(id, HandleAgreeStr)
      await Home.HandleOppose(id, HandleOpposeStr)
      code.data = 1
      code.message = '修改成功'
      res.send(code)
    }
  } catch (error) {
    err_code.message = error
    res.send(err_code)
  }
}


// 异常响应函数
function catchFn(err, res){
  err_code.message = err
  res.send(err_code)
}